import { Controller } from 'egg';

export default class UserController extends Controller {
  async index() {
    const { ctx } = this;
    // ctx.throwBizError({code:403, message: '请上传图片格式的文件', log: false, status: 403});
    const users = await ctx.model.User.scope('deleted').findAll();
    ctx.ok(users);
  }
  // 登录
  async login() {
    const { app, ctx, service } = this;
    const { username, password } = ctx.request.body;
    const result = await service.user.doLogin({
      username,
      password,
    });
    const opts = {
      path: '/',
      maxAge: 1000 * 60 * 60 * 24 * 30,   // cookie 有效期30天
      httpOnly: false,
      domain: '127.0.0.1',
    };
    ctx.cookies.set(app.config.auth_cookie_name, result.token, opts);
    ctx.ok(result);
  }
  // 注册
  async regist() {
    const { ctx, service } = this;
    await service.user.create(ctx.request.body);
    ctx.ok(null, '注册成功');
  }
  // 关注用户
  async toggleFollow() {
    const { ctx, service } = this;
    const userId = ctx.params.userId;
    const meId = ctx.userId;
    if (userId === meId) {
      ctx.fail('您不能关注自己哦')
      return;
    }
    const user = await ctx.model.User.findByPk(userId);
    if (!user) {
      ctx.fail('用户不存在', 46004)
      return;
    }
    const isFollow = await service.user.toggleFollow(meId, Number(userId));
    const message = isFollow ? '关注成功' : '取消关注';
    ctx.ok({ isFollow }, message);
  }
  // 获取登录用户信息
  async getLoginUserBasicInfo() {
    const { ctx, service } = this;
    const userId = ctx.userId;
    const result = await service.user.getBasicInfo(userId);
    ctx.ok(result);
  }
  //批量获取用户信息
  async batchGetUserInfo() {
    const { ctx, service } = this;
    let { userIds } = ctx.query;
    const data: any = await Promise.all(userIds.split(',').map(userId => {
      return service.user.getUserInfo(userId);
    })); 
    let result = {}
    data.forEach(item => {
      result[item.id] = item
    })
    ctx.ok(result);
  }

  async update() {
    const { ctx, service } = this;
    const userId = ctx.userId;
    await service.user.doUpdate(userId, ctx.request.body);
    ctx.ok();
  }
  //更新用户头像
  async updateAvatar() {
    const { ctx, service } = this;
    const userId = ctx.userId;
    const stream = await ctx.getFileStream();
    const imgTypes = ['jpg', 'png', 'gif', 'jpeg'];
    const filename = stream.filename;
    const nameArray = filename.split('.');
    const type = nameArray[nameArray.length - 1];
    if (imgTypes.indexOf(type) === -1) {
      ctx.fail('请上传图片格式的文件', 40005)
      // ctx.throwBizError({ message: '请上传图片格式的文件', log: false });
      return;
    }
    const { url } = await service.base.upload(stream);
    await service.user.doUpdate(userId, { avatar: url });
    ctx.ok({ url }, '更新成功');
  }
}
